import { createRoot } from "react-dom/client";
import App, { UIController } from "../App";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";
import CssBaseline from "@mui/material/CssBaseline";
import { ThemeProvider } from "@mui/material/styles";
import { appTheme } from "@utils/theme";
import { bindController } from "../components/PlusButtons";

export function mountReactApp() {
  const host = document.createElement("div");
  host.id = "wxt-react-host";
  const shadow = host.attachShadow({ mode: "open" });
  const container = document.createElement("div");
  shadow.appendChild(container);
  document.body.appendChild(host);

  let controller: UIController | null = null;

  const root = createRoot(container);
  const emotionCache = createCache({ key: "wxt", prepend: true, container: shadow as unknown as HTMLElement });
  root.render(
    <CacheProvider value={emotionCache}>
      <ThemeProvider theme={appTheme}>
        <CssBaseline />
        <App
          onReady={(c) => {
            controller = c;
            bindController(c);
          }}
        />
      </ThemeProvider>
    </CacheProvider>
  );

  return {
    extensionPanel: { toggle: () => controller?.togglePanel() },
    floatingButton: {},
  } as any;
}
